package com.lungle.warmdiary.app.view.active.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.HttpHelper;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.request.ActiveCommentUpdatePost;
import com.lungle.warmdiary.app.model.response.Active;
import com.lungle.warmdiary.app.model.response.Image;
import com.lungle.warmdiary.app.ui.widget.AutoGridView;
import com.lungle.warmdiary.app.utils.DateUtil;
import com.lungle.warmdiary.app.view.active.adapter.CommentDetailAdapter;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


public class CommentDetailScreenShotFragment extends BaseFragment implements GridView.OnItemClickListener {
    private static final String COMMENT_DETAIL_SCREEN = "comment detail screen";
    public final int MAX_UPLOAD = 10;
    private List<String> mDisplayImaged = new ArrayList<>();
    private List<String> mNeedUploadImages = new ArrayList<>();
    private List<String> mNeedReplaceImages = new ArrayList<>();
    private List<String> mUploadResult = new ArrayList<>();


    @Bind(R.id.gv_images)
    AutoGridView mGvImages;

    private CommentDetailAdapter mAdapter;
    private Active mActive;

    private boolean isUpdate = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.v2_fragment_commet_detail_screenshot, container, false);
        initData();
        initViews(view);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(COMMENT_DETAIL_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(COMMENT_DETAIL_SCREEN);
        MobclickAgent.onPause(getActivity());

    }

    @Override
    public void initData() {
        mActive = (Active) getArguments().getSerializable("active");
        if (DateUtil.isThreeDayLater(DateUtil.getDate(mActive.getEndtime()), HttpHelper.getServerTime())) {
            isUpdate = false;
        } else {
            isUpdate = true;
        }

    }

    private void initViews(View view) {
        ButterKnife.bind(this, view);

        if (mActive.getResultScreenshot2() != null) {
            for (String url : mActive.getResultScreenshot2()) {
                mDisplayImaged.add(url);
            }
        }
        mAdapter = new CommentDetailAdapter(getActivity(), mDisplayImaged);
        mGvImages.setAdapter(mAdapter);
        mGvImages.setOnItemClickListener(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (isUpdate) {
            getActivity().getMenuInflater().inflate(R.menu.active_detail, menu);
            menu.findItem(R.id.login_menu_send);
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (prepareSubmit()) {

            Observable.from(mNeedUploadImages).subscribe(new Action1<String>() {
                @Override
                public void call(String url) {
                    uploadAndUpdate(url);
                }
            });

        }

        return true;
    }


    private final int CODE_MUL_SELECT = 1;
    private final int CODE_SHOW = 2;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (data != null) {
            List<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            if (requestCode == CODE_MUL_SELECT) {
                if (photos == null && photos.isEmpty()) return;
                for (String path : photos) {
                    mDisplayImaged.add(path);
                    mNeedReplaceImages.add(path);

                }
                mAdapter.notifyDataSetChanged();
            } else if (requestCode == CODE_SHOW) {
                mDisplayImaged.clear();
                mDisplayImaged.addAll(photos);
                mAdapter.notifyDataSetChanged();
            }
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (!isUpdate) {
            try {

                PhotoPreview.builder()
                        .setPhotos((ArrayList) mDisplayImaged)
                        .setCurrentItem(position)
                        .setShowDeleteButton(false)
                        .start(getActivity(), this, CODE_SHOW);
            } catch (Exception e) {
                //nothing  
            }
            return;
        }

        int count = parent.getCount();
        int realCount = mAdapter.getRealCount();
        if (count != realCount) {

            if (position == count - 1) {//点击图片
                int remain = MAX_UPLOAD - count + 1;
                PhotoPicker.builder()
                        .setPhotoCount(remain)
                        .setShowCamera(false)
                        .start(getActivity(), this, CODE_MUL_SELECT);

            } else {
                PhotoPreview.builder()
                        .setPhotos((ArrayList) mDisplayImaged)
                        .setCurrentItem(position)
                        .setShowDeleteButton(true)
                        .start(getActivity(), this, CODE_SHOW);
            }

        } else {
            PhotoPreview.builder()
                    .setPhotos((ArrayList) mDisplayImaged)
                    .setCurrentItem(position)
                    .setShowDeleteButton(true)
                    .start(getActivity(), this, CODE_SHOW);

        }


    }

    private boolean prepareSubmit() {
        for (String uri : mDisplayImaged) {
            if (!uri.startsWith("http")) {
                mNeedUploadImages.add(uri);
            }
        }
        return !mNeedUploadImages.isEmpty();

    }

    private void uploadAndUpdate(String url) {
        showWaitDialog();
        File file = new File(url);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        ApiFactory.getFileApi().upload(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<Image>>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        if (mNeedUploadImages.isEmpty()) {
                            hideWaitDialog();

                            mActive.setResultScreenshot2(merge(mActive.getResultScreenshot2(), mUploadResult));

                            //                            mActive.setResultScreenshot2( mUploadResult);
                            if (canUpdateActiveState()) {

                                updateActiveState();
                            } else {
                                setResultData();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //                        super.onError(e);
                        AppContext.showToast("上传失败");
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<Image> result) {
                        mNeedUploadImages.remove(url);
                        mUploadResult.add(result.getData().getUrl());
                    }
                });
    }


    private List<String> merge(List<String> oldUrls, List<String> newUrls) {
        List<String> mergeList = new ArrayList<>();

        if (oldUrls != null) {
            oldUrls.removeAll(newUrls);
            oldUrls.addAll(newUrls);
            mergeList.addAll(oldUrls);
        } else {
            mergeList.addAll(newUrls);
        }

        mergeList.removeAll(mNeedReplaceImages);

        return mergeList;
    }


    private boolean canUpdateActiveState() {

        if (!TextUtils.isEmpty(mActive.getResultScreenshot1()) && mActive.getResultScreenshot2() != null) {
            return true;
        }
        return false;

    }


    private void setResultData() {
        Intent intent = new Intent();
        intent.putExtra(ActiveDetailFragment.ARGS_RESPONSE, mActive);
        getActivity().setResult(ActiveDetailFragment.CODE_RESPONSE_DETAIL, intent);
        getActivity().finish();
    }


    private void updateActiveState() {
        showWaitDialog("正在更新活动");
        ActiveCommentUpdatePost.CampaignProcess campaignProcess = new ActiveCommentUpdatePost.CampaignProcess(mActive.getNcomment(),
                mActive.getNlike(), mActive.getResultScreenshot2(), mActive.getResultScreenshot1());
        ActiveCommentUpdatePost campaignProcessPost = new ActiveCommentUpdatePost(campaignProcess);
        ApiFactory.getUserApi().updateActiveState(mActive.getId(), mActive.getMediaid(), campaignProcessPost).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        setResultData();
                        hideWaitDialog();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result result) {
                        AppContext.showToast("更新成功");
                    }
                });
    }


}
